// pages/number/index.js
import {
  list,
  add,
  update,
  remove
} from '../../api/number'
import {
  valueType,
  numSettingsType
} from '../../dataSource'
import Notify from '../../miniprogram_npm/@vant/weapp/notify/notify';
import {
  useToast
} from '../../miniprogram_npm/miniprogram-vc-components/toast/useToast';
import {
  useDialog
} from '../../miniprogram_npm/miniprogram-vc-components/dialog/useDialog';

let toast, dialog;

Page({
  options: {
    pureDataPattern: /^_/
  },
  /**
   * 页面的初始数据
   */
  data: {
    dataSource: [],
    newSourceObj: {
      activeIndex: null,
      remarkIndex: null,
      showModal: false
    },
    remark: {
      temp: '',
    },
    valueType,
    name: '',
    _key: ''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.initPage(options);
    this.fetchData();
  },
  initPage(opts) {
    this.setData({
      _key: opts.key
    })
    const setPageTitle = (title) => {
      wx.setNavigationBarTitle({
        title
      })
    }
    switch (opts.key) {
      case numSettingsType.RECORD:
        setPageTitle('采集记录编号设置')
        break;
      case numSettingsType.INGREDIENTS:
        setPageTitle('原料编号设置');
        break;
      case numSettingsType.RECIPE:
        setPageTitle('配方编号设置');
        break;
      default:
        break;
    }
  },
  onSearchNameChange(event) {
    this.setData({
      name: event.detail
    })
  },
  onClear() {
    this.setData({
      name: ''
    })
    this.fetchData();
  },
  fetchData() {
    list({
      name: this.data.name,
      numSettingsType: numSettingsType[this.data._key],

    }, (e) => {
      this.setData({
        dataSource: e?.sort((a, b) => {
          return a.sortNumber - b.sortNumber;
        })
      })
    })
  },
  canAddItem() {
    return !this.data.dataSource.some(it => it.state === false)
  },
  add() {
    const arr = [...this.data.dataSource];
    if (this.canAddItem()) {
      arr.push({
        name: "",
        numSettingsType: numSettingsType[this.data._key],
        valueType: "",
        sortNumber: this.getSortNumber(),
        remark: "",
        state: false
      })
      this.setData({
        dataSource: arr
      })
    } else {
      Notify({
        type: 'warning',
        message: '请先保存或移除上一次添加的内容'
      });
    }
  },
  toNumberSelect(event) {
    const item = encodeURIComponent(JSON.stringify(event.currentTarget.dataset.item));

    wx.navigateTo({
      url: '../number-select/index?data=' + item,
    })
  },
  onNewSourceChangeName(event) {
    const {
      dataSource
    } = this.data;
    const index = event.detail.params[0],
      value = event.detail.value;
    dataSource[index].name = value;
    this.setData({
      dataSource
    })
  },
  /**
   * 选择数据
   * @param {*} event 
   * event.detail @ Array<String>
   */
  onNewSourceChangeSelect(event) {
    const {
      dataSource
    } = this.data,
      index = event.currentTarget.dataset.index,
      value = event.detail[0];
    dataSource[index].valueType = value;
    this.setData({
      dataSource
    })
  },
  /**
   * 计算得到sortNumber
   */
  getSortNumber() {
    const {
      dataSource
    } = this.data;
    return dataSource.length + 1
  },
  toggleNewSourceVisible(event) {
    const sortNumber = event.currentTarget.dataset.sort_number;

    this.setData({
      newSourceObj: {
        ...this.data.newSourceObj,
        activeIndex: sortNumber === this.data.newSourceObj.activeIndex ? null : sortNumber
      }
    })
  },
  onRemark(event) {
    const {
      dataSource
    } = this.data,
      index = event.currentTarget.dataset.index,
      value = dataSource[index].remark;
    this.setData({
      remark: {
        temp: value
      },
      newSourceObj: {
        ...this.data.newSourceObj,
        remarkIndex: index,
        showModal: true
      }
    })
  },

  onRemarkChange(event) {
    this.setData({
      remark: {
        temp: event.detail
      },
    })
  },
  onRemarkCancel() {
    this.setData({
      newSourceObj: {
        ...this.data.newSourceObj,
        showModal: false
      },
      remark: {
        temp: ''
      }
    })
  },
  onRemarkConfirm() {
    const {
      dataSource,
      newSourceObj
    } = this.data;
    dataSource[newSourceObj.remarkIndex].remark = this.data.remark.temp;
    this.onRemarkCancel();
  },
  isEmpty(obj) {
    return !obj.name || !obj.valueType;
  },
  onSave(event) {
    const index = event.currentTarget.dataset.index,
      {
        dataSource,
      } = this.data,
      item = dataSource[index];

    if (this.isEmpty(item)) {
      toast.init({
        value: "名称或格式不正确"
      }).open();
    } else {
      delete item.state;
      item.id === undefined ?
        add(item, () => {
          Notify({
            type: 'success',
            message: '已保存'
          });
          this.fetchData();
        }, this.fetchData) : update(item, () => {
          Notify({
            type: 'success',
            message: '已保存'
          });
        })
    }
  },
  onRemove(event) {
    const index = event.currentTarget.dataset.index,
      {
        dataSource,
      } = this.data,
      item = dataSource[index];
    if (item.id === undefined) {
      this.viewRemove(dataSource, index);
    } else {
      const dialogInstance = dialog.init({
        title: "",
        content: "确定要移除此配置吗？",
        icon: "icon-warning",
        showCancel: true,
        mask: true
      }, () => {
        remove(item, () => {
          Notify({
            type: 'success',
            message: '已删除'
          });
          dialogInstance.close();
          this.fetchData();
          this.viewRemove(dataSource, index);
        })
      }, () => dialogInstance.close())
      dialogInstance.open();
    }
  },
  viewRemove(dataSource, index) {
    const d = dataSource.filter((_, i) => {
      return i !== index;
    })
    this.setData({
      dataSource: d
    })
    this.hideMoreButton();
  },
  hideMoreButton() {
    this.setData({
      newSourceObj: {
        ...this.data.newSourceObj,
        activeIndex: null
      }
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {
    toast = useToast('#toast', this);
    dialog = useDialog('#dialog', this);
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})